<template>
  <div class="tools-container">
    <a-row>
      <a-space>
        <a-col :span="4" v-if="!isUploaded">
          <a-upload :action="Activity" :limit="1" :show-remove-button="false" :onError="onError" :onProgress="onProgress"
            :onSuccess="onSuccess" @before-upload="beforeUpload" />
        </a-col>
        <a-col :span="4" v-if="isUploaded">
          <a-button :disabled="progress != 0 && progress != 1" :loading="progress != 0 && progress != 1" type="primary" status="warning" @click="submitDevlopy">
            <template #icon>
              <icon-dashboard />
            </template>
            <template #default>开始部署</template>
          </a-button>
        </a-col>
        <a-col :span="4" v-if="percent == 1">
          <a-button type="primary" status="success" @click="getRegStatus">
            <template #icon>
              <icon-find-replace />
            </template>
            <template #default>查询状态</template>
          </a-button>
        </a-col>
        <a-col :span="4" v-if="percent == 1">
          <a-popover title="删除提示">
            <a-button type="primary" status="danger" @click="delFolderFileFun">
              <template #icon>
                <icon-delete />
              </template>
              <template #default>删除更新文件</template>
            </a-button>
            <template #content>
              <p>该操作不会删除已上传的文件</p>
              <p>只会删除上传完解压后的文件</p>
              <p>确保部署没有问题后，即可删除</p>
            </template>
          </a-popover>
        </a-col>
      </a-space>

      <a-col class="mrt" :span="22" v-if="!isUploaded">
        上传进度
        <a-progress :color="{
          '0%': 'rgb(var(--primary-6))',
          '100%': 'rgb(var(--success-6))',
        }" :show-text="true" :percent="percent" />
      </a-col>
      <a-col class="mrt" :span="22" v-if="progress != 0">
        部署进度
        <a-progress :steps="5" status="warning" :percent="progress" />
      </a-col>
      <a-col class="mrt" :span="22" v-if="percent == 1">
        <a-table :columns="regColumns" :data="regData" />
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { fileUnzip, fileBackup, readRestLog,delFolderFile, fileUnzipUpd, restartServer, fileDistribute, getEurkaStatus } from "@/api/index.js";
import { IconDashboard, IconFindReplace,IconDelete } from "@arco-design/web-vue/es/icon";
import dayjs from "dayjs";
export default {
  components: {
    IconDashboard,
    IconFindReplace,
    IconDelete
  },
  data() {
    return {
      percent: 0,
      progress: 0,
      isUploaded: false,
      isBegDev: false,
      fileName: "",
      Activity: import.meta.env.VITE_BASE_SERVER_URL + "/upload",
      regColumns: [
        {
          title: "服务名",
          dataIndex: "name",
        },
        {
          title: "端口",
          dataIndex: "port",
        },
        {
          title: "所在IP",
          dataIndex: "ipAddr",
        },
        {
          title: "启动状态",
          dataIndex: "status",
        },
      ],
      regData: [],
    };
  },
  methods: {
    delFolderFileFun() {
      delFolderFile({
        folderPath: "",
        type: "devlopy"
      })
        .then((res) => {
          console.log("删除文件==");
          console.log(res);
          console.log("删除文件==");
          if (res.status == 200) {
            this.$toast.open({
              message: res.data,
              type: "success",
              duration: 3000,
              position: "top-right",
            });
            return true;
          }
        })
        .catch((error) => {
          this.$toast.open({
            message: "失败，请检查控制台日志！",
            type: "error",
            duration: 3000,
            position: "top-right",
          });
          console.log(error);
        })
    },
    fileUnzipFun() {
      fileUnzip({
        cookie: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
        fileName: "app.tar"
      })
        .then((res) => {
          console.log("解压文件==");
          console.log(res);
          console.log("解压文件==");
          if (res.status == 200) {
            this.$toast.open({
              message: res.data,
              type: "success",
              duration: 3000,
              position: "top-right",
            });
            return true;
          }
        })
        .catch((error) => {
          this.$toast.open({
            message: "失败，请检查控制台日志！",
            type: "error",
            duration: 3000,
            position: "top-right",
          });
          console.log(error);
        })
    },
    fileDistributeFun() {
      fileDistribute({
        cookie: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
      })
        .then((res) => {
          console.log("分发文件==");
          console.log(res);
          console.log("分发文件==");
          if (res.status == 200) {
            this.$toast.open({
              message: res.data,
              type: "success",
              duration: 3000,
              position: "top-right",
            });
            return true;
          }
        })
        .catch((error) => {
          this.$toast.open({
            message: "失败，请检查控制台日志！",
            type: "error",
            duration: 3000,
            position: "top-right",
          });
          console.log(error);
        })
    },
    fileBackupFun() {
      fileBackup({
        cookie: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
      })
        .then((res) => {
          console.log("备份文件==");
          console.log(res);
          console.log("备份文件==");
          if (res.status == 200) {
            this.$toast.open({
              message: res.data,
              type: "success",
              duration: 3000,
              position: "top-right",
            });
            return true;
          }
        })
        .catch((error) => {
          this.$toast.open({
            message: "失败，请检查控制台日志！",
            type: "error",
            duration: 3000,
            position: "top-right",
          });
          console.log(error);
        })
    },
    fileUnzipUpdFun() {
      fileUnzipUpd({
        cookie: dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss"),
      })
        .then((res) => {
          console.log("解压分发文件==");
          console.log(res);
          console.log("解压分发文件==");
          if (res.status == 200) {
            this.$toast.open({
              message: res.data,
              type: "success",
              duration: 3000,
              position: "top-right",
            });
            return true;
          }
        })
        .catch((error) => {
          this.$toast.open({
            message: "失败，请检查控制台日志！",
            type: "error",
            duration: 3000,
            position: "top-right",
          });
          console.log(error);
        })
    },
    restartServerFun() {
      restartServer({
        "mode": "normal",
        "server": [],
        "type": "devlopy" // restart devlopy devlopy时，后端自动读取文件
      })
        .then((res) => {
          console.log("重启==");
          console.log(res);
          console.log("重启==");
          if (res.status == 200) {
            this.$toast.open({
              message: res.data,
              type: "success",
              duration: 3000,
              position: "top-right",
            });
            return true;
          }
        })
        .catch((error) => {
          this.$toast.open({
            message: "失败，请检查控制台日志！",
            type: "error",
            duration: 3000,
            position: "top-right",
          });
          console.log(error);
        })
    },
    submitDevlopy() {
      // TODO:pinia存储是否已经上传文件，并保存文件名 https://juejin.cn/post/7213994684262891576
      // 1. 调用解压方法，去解压，停顿 10 s unzip
      // 2. 调用分发方法，分发文件，停10s 
      // 3. 调用备份方法，备份文件，停10S
      // 4. 调用解压分发文件到各服务器，停10S
      // 5. 调用重启方法
      this.isBegDev = true;
      let that = this;
      const pp = new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('1');
          that.progress = 0.2;
          that.fileUnzipFun();
        }, 1000)
      }).then(res => {
        console.log('res1', res) //1秒后打印 a
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve(res + '2')
            that.progress = 0.4;
            that.fileDistributeFun();
          }, 1000)
        })
      }).then(res => {
        console.log('res', res) //2秒后打印 aa
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve(res + '3')
            that.progress = 0.6;
            that.fileBackupFun();
          }, 1000)
        })
      }).then(res => {
        console.log('res', res) //2秒后打印 aa
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve(res + '4')
            that.progress = 0.8;
            that.fileUnzipUpdFun();
          }, 1000)
        })
      }).then(res => {
        console.log('res', res) //2秒后打印 aa
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve(res + '5')
            that.progress = 1;
            that.restartServerFun();
          }, 1000)
        })
      }).catch(err => {
        console.log('err', err)//1秒后打印 error message
        that.progress = 0;
      })
    },
    // 上传前校验
    beforeUpload(resolve) {
      let name = ["zip", "tar"];
      let fileName = resolve.name.split(".");
      let fileExt = fileName[fileName.length - 1];
      let isTypeOk = name.indexOf(fileExt) >= 0;
      if (!isTypeOk) {
        this.$toast.open({
          message: "仅支持上传 zip、tar 文件",
          type: "error",
          duration: 6000,
          position: "top-right",
        });
      } else {
        this.fileName = resolve.name;
        return new Promise((resolve) => {
          resolve(true);
        });
      }
    },
    onError(err) {
      // console.log("--- onError ---");
      // console.log(err);
      // console.log(err.name);
      // console.log("--- onError ---");
      this.$toast.open({
        message: err.name + " 上传失败！",
        type: "error",
        duration: 6000,
        position: "top-right",
      });
    },
    onSuccess(response) {
      // console.log("--- onSuccess ---");
      // console.log(response);
      // console.log("--- onSuccess ---");
      this.$toast.open({
        message: "文件正在上传！",
        type: "success",
        duration: 3000,
        position: "top-right",
      });
      this.isUploaded = true;
    },
    onProgress(file, event) {
      let ProgressEvent = event;
      let complete = parseInt((ProgressEvent.loaded / ProgressEvent.total) | 0);
      this.percent = complete;
      if (this.percent == 1) {
        this.$toast.open({
          message: "文件上传完成！",
          type: "success",
          duration: 3000,
          position: "top-right",
        });
        this.isUploaded = true;
      }
    },
    getRegStatus(type = "eurka") {
      // console.log(type);
      // TODO:根据不同的类型去查询，目前没找到consul的实现
      // 点击了请求，先清理已有的数据
      this.regData = [];
      getEurkaStatus(null)
        .then((res) => {
          // console.log(res);
          // 请求到数据，然后封装数据进行展示
          // 获取到 application 数组
          let application = res.data.data.applications.application;
          // console.log(application);
          // 获取字段 ,封装在数据中
          application.forEach((element) => {
            // 定义临时的对象
            let obj = {
              name: element.name,
              port: element.instance[0].port.$,
              ipAddr: element.instance[0].ipAddr,
              status: element.instance[0].status,
            };
            this.regData.push(obj);
          });
        })
        .catch((error) => {
          console.log(error);
          this.$toast.open({
            message: error,
            type: "error",
            duration: 6000,
            position: "top-right",
          });
        });
    },
  },
  mounted() { },
};
</script>

<style lang="scss" scoped></style>
